import { watch } from 'vue'
import { useRoute } from 'vue-router'
import throttle from 'lodash/throttle'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { EditCanvasTypeEnum } from '@/store/modules/chartEditStore/chartEditStore.d'
import { useSync } from '@/views/chart/hooks/useSync.hook'
import { ChartEnum } from '@/enums/pageEnum'
import { SavePageEnum } from '@/enums/editPageEnum'
import { editToJsonInterval } from '@/settings/designSetting'
import { goDialog, fetchRouteParamsLocation, getSessionStorage, setSessionStorage } from '@/utils'
import html2canvas from 'html2canvas'
import { BSupload, BASE_URL } from '@/api/screen'
import { contentModify, contentAdd, projectModify } from '@/api/screen'
import project from '@/i18n/zh/project'
const { updateComponent } = useSync()
const chartEditStore = useChartEditStore()

const fetchProhectInfoById = () => {
  const id = fetchRouteParamsLocation()
  console.log('id', id)
  if (id.length) {
    return id
  }
  return ''
}

const createThumb = () => {
  const designContainer = document.querySelector('.go-edit-range') as HTMLElement
  chartEditStore.setTargetSelectChart(undefined)
  setTimeout(() => {
    html2canvas(designContainer, {
      // backgroundColor: null,
      // allowTaint: true,
      scale: 1,
      useCORS: true
    }).then((canvas: HTMLCanvasElement) => {
      generateThumbnail(canvas).then(blob => {
        console.log('blob', blob)
        const formData = new FormData()
        formData.append('file', blob, 'thumbnail.png')
        formData.append('storeFolder', 'bigscreen')

        let projectSid = fetchProhectInfoById()
        BSupload(formData).then(res => {
          if (res.code == 200) {
            let indexImage = res.data
            projectModify({ sid: projectSid, indexImage }).then(res => {
              // window['$message'].success('缩略图保存')
              console.log('缩略图保存成功')
            })
          } else {
            console.error('缩略图保存失败')
            // window['$message'].success('缩略图失败')
          }
        })
      })
    })
  }, 600)
}
const generateThumbnail = async (canvas: any) => {
  return new Promise(resolve => {
    const thumbnailCanvas = document.createElement('canvas')
    const ctx = thumbnailCanvas.getContext('2d')

    // 设置缩略图尺寸
    const maxWidth = 300 // 缩略图最大宽度
    const maxHeight = 200 // 缩略图最大高度
    let width = canvas.width
    let height = canvas.height

    // 按比例缩放
    if (width > maxWidth) {
      height *= maxWidth / width
      width = maxWidth
    }
    if (height > maxHeight) {
      width *= maxHeight / height
      height = maxHeight
    }

    // 设置缩略图 canvas 尺寸
    thumbnailCanvas.width = width
    thumbnailCanvas.height = height

    // 绘制缩略图
    ctx.drawImage(canvas, 0, 0, width, height)

    // 将缩略图转换为 Blob 或 Data URL
    thumbnailCanvas.toBlob(blob => {
      resolve(blob)
    }, 'image/png')
  })
}

export const syncData = () => {
  let projectInfo = getSessionStorage('projectInfo')
  let content = chartEditStore.getStorageInfo()

  if (projectInfo.designModelSid) {
    contentModify({ sid: projectInfo.designModelSid, content }).then(res => {
      if (res.code == 200) {
        window['$message'].success('设计内容更新成功')
        createThumb()
      } else {
        window['$message'].error('设计内容更新失败')
      }
    })
  } else {
    contentAdd({ content, note: `${projectInfo.sid}大屏设计模型` }).then(res => {
      if (res.code == 200) {
        let designModelSid = res.data
        projectInfo.designModelSid = designModelSid
        setSessionStorage('projectInfo', projectInfo)
        projectModify({ sid: projectInfo.sid, designModelSid }).then(res => {
          if (res.code == 200) {
            window['$message'].success('更新成功')
          } else {
            window['$message'].error('更新失败')
          }
        })
      } else {
        window['$message'].error('设计内容保存失败')
      }
    })
  }

  // goDialog({
  //   message: '是否覆盖原视图内容，此操作不可撤回?',
  //   isMaskClosable: true,
  //   transformOrigin: 'center',
  //   onPositiveCallback: () => {
  //     window['$message'].success('正在保存...')
  //     dispatchEvent(new CustomEvent(SavePageEnum.CHART, { detail: chartEditStore.getStorageInfo() }))
  //   }
  // })
}

// 同步数据到预览页
export const syncDataToPreview = () => {
  dispatchEvent(new CustomEvent(SavePageEnum.CHART_TO_PREVIEW, { detail: chartEditStore.getStorageInfo() }))
}

// 侦听器更新
const useSyncUpdateHandle = () => {
  // 定义侦听器变量
  let timer: any

  // 更新处理
  const updateFn = (e: any) => {
    window['$message'].success('正在进行更新...')
    updateComponent(e!.detail, true)
  }

  // 页面关闭处理
  const closeFn = () => {
    chartEditStore.setEditCanvas(EditCanvasTypeEnum.IS_CODE_EDIT, false)
  }

  // 开启侦听
  const use = () => {
    // 定时同步数据（暂不开启）
    // timer = setInterval(() => {
    //   // 窗口激活并且处于工作台
    //   document.hasFocus() && syncData()
    // }, editToJsonInterval)

    // 失焦同步数据
    addEventListener('blur', syncDataToPreview)

    // 监听编辑器保存事件 刷新工作台图表
    addEventListener(SavePageEnum.JSON, updateFn)

    // 监听编辑页关闭
    addEventListener(SavePageEnum.CLOSE, throttle(closeFn, 1000))
  }

  // 关闭侦听
  const unUse = () => {
    // clearInterval(timer)
    removeEventListener('blur', syncDataToPreview)
    removeEventListener(SavePageEnum.JSON, updateFn)
  }

  // 路由变更时处理
  const watchHandler = (toName: any, fromName: any) => {
    if (fromName == ChartEnum.CHART_HOME_NAME) {
      unUse()
    }
    if (toName == ChartEnum.CHART_HOME_NAME) {
      use()
    }
  }

  return watchHandler
}

export const useSyncUpdate = () => {
  const routerParamsInfo = useRoute()
  watch(() => routerParamsInfo.name, useSyncUpdateHandle(), { immediate: true })
}
